package com.cskaoyan.service.vx.order;

import com.cskaoyan.bean.bo.vxBo.CartToOrderBO;
import com.cskaoyan.bean.bo.vxBo.VXCommentBO;
import com.cskaoyan.bean.po.wxPo.*;
import com.cskaoyan.bean.vo.TVO;
import com.cskaoyan.bean.vo.vxVo.*;
import com.cskaoyan.mapper.transfer.MarketCart2OrderGoodsMapper;
import com.cskaoyan.mapper.transfer.MarketCommentPOMapper;
import com.cskaoyan.mapper.transfer.MarketOrderDetailGoodsVOMapper;
import com.cskaoyan.mapper.transfer.MarketOrderDetailVOMapper;
import com.cskaoyan.mapper.wxMapper.*;
import com.cskaoyan.service.vx.order.WXOrderService;
import com.cskaoyan.util.OrderSnUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.font.TrueTypeFont;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author by WANGJun
 * @date 2022/6/7 14:42
 */
@Service
public class WXOrderServiceImpl implements WXOrderService {

    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketAftersaleMapper marketAftersaleMapper;


    /**
     * market_comment表新增
     * market_order_goods表修改content为comment表的id
     *
     * @param vXCommentBO
     * @return
     */
    @Override
    public int comment(VXCommentBO vXCommentBO) {
        MarketComment comment = MarketCommentPOMapper.INSTANCE.po2Vo(vXCommentBO);
        comment.setType(0);
        comment.setDeleted(false);
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        comment.setUserId(marketUser.getId());
        comment.setPicUrls(vXCommentBO.getPicUrls().toString());
        comment.setAddTime(new Date());
        //System.out.println("vXCommentBO.getOrderGoodsId()"+vXCommentBO.getOrderGoodsId());
        if (vXCommentBO.getOrderGoodsId() != null) {
            MarketOrderGoodsExample example2 = new MarketOrderGoodsExample();
            example2.createCriteria().andIdEqualTo(vXCommentBO.getOrderGoodsId());
            Integer goodsId = marketOrderGoodsMapper.selectByExample(example2).get(0).getGoodsId();
            comment.setValueId(goodsId);
        } else {
            comment.setValueId(0);
        }
        int i1 = marketCommentMapper.insertReturnId(comment);
        Integer commentId = comment.getId();
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        example.createCriteria().andIdEqualTo(vXCommentBO.getOrderGoodsId());
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setComment(commentId);
        int i = marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods, example);
        System.out.println(i1 + "," + i);
        //修改market_order
        Integer orderId = marketOrderGoodsMapper.selectByPrimaryKey(vXCommentBO.getOrderGoodsId()).getOrderId();
        Short oldComments = marketOrderMapper.selectByPrimaryKey(orderId).getComments();
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.createCriteria().andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setComments((short)(oldComments-1)>=0?(short)(oldComments-1):0);
        //marketOrder.setComments(0);
        marketOrderMapper.updateByExampleSelective(marketOrder, marketOrderExample);
        return i + i1;
    }

    /**
     * OrderListVO
     * private String orderStatusText;
     * private int aftersaleStatus;
     * private boolean isGroupin;
     * private String orderSn;
     * private int actualPrice;
     * private int id;
     * private HandleOptionBean handleOption;
     * private List<OrderListGoodsVO> goodsList;
     *
     * @param showType
     * @param page
     * @param limit
     * @return
     */
    @Override
    public TVO<OrderListVO> list(Short showType, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        //查询非list部分
        // MarketOrderExample marketOrderExample = new MarketOrderExample();
        // marketOrderExample.createCriteria().andOrderStatusBetween((short) (showType*100),(short)(showType*100+99));
        // List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        // //map(MarketOrder,OrderList)
        // List<OrderListVO> orderListVOS = MarketOrderVOMapper.INSTANCE.po2Vo(marketOrders);
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        List<OrderListVO> orderListVOS = marketOrderMapper.selectByShowType((int) showType,marketUser.getId());
        System.out.println(orderListVOS.size());
        //查询handleOptionBean
        Iterator<OrderListVO> iterator = orderListVOS.iterator();
        while (iterator.hasNext()) {
            OrderListVO next = iterator.next();
            HandleOptionBean handleOptionBean = HandleOptionBean.data(next.getOrderStatus(), next.getAftersaleStatus(), next.getComment());
            next.setHandleOption(handleOptionBean);
            //next.setOrderStatusText(null);
            next.setIsGroupin(false);
            next.setDeleted(false);
            next.setComment(null);
        }
        PageInfo pageInfo = new PageInfo(orderListVOS);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return TVO.data(total, pages, limit, page, orderListVOS);
    }

    @Override
    public OrderDetailVO detail(Integer orderId) {
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        //OrderInfoBean + List + List(OrderDetailGoodsVO
        //OrderInfoBean(HandleOptionBean)
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        OrderInfoBean orderInfo = MarketOrderDetailVOMapper.INSTANCE.po2Vo(marketOrder);
        HandleOptionBean handleOptionBean = HandleOptionBean.data((int) marketOrder.getOrderStatus(), (int) marketOrder.getAftersaleStatus(), (int) marketOrder.getComments());
        orderInfo.setHandleOption(handleOptionBean);
        orderDetailVO.setOrderInfo(orderInfo);
        //List
        orderDetailVO.setExpressInfo(new ArrayList<>());
        //List(OrderDetailGoodsVO)
        //注意：这里的查询结果包含已删除order_goods
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);
        List<OrderDetailGoodsVO> orderDetailGoodsVOS = MarketOrderDetailGoodsVOMapper.INSTANCE.po2Vo(marketOrderGoods);
        orderDetailVO.setOrderGoods(orderDetailGoodsVOS);
        return orderDetailVO;
    }

    @Override
    public void cancel(Integer orderId) {
        // Integer statusId = 102;
        // marketOrderMapper.updateOrderStatus(orderId, statusId);
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short) 102);
        marketOrder.setConfirmTime(new Date());
        marketOrderMapper.updateByExampleSelective(marketOrder, orderExample);
    }

    @Override
    public void refund(Integer orderId) {
        //market_order
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short) 202);
        marketOrder.setRefundTime(new Date());
        marketOrderMapper.updateByExampleSelective(marketOrder, orderExample);
        //market_aftersale
        MarketAftersale marketAftersale = new MarketAftersale();
        marketAftersale.setOrderId(orderId);
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        marketAftersale.setUserId(marketUser.getId());
        marketAftersale.setType((short) 0);
        marketAftersale.setAmount(marketOrderMapper.selectByPrimaryKey(orderId).getActualPrice());
        marketAftersale.setStatus((short) 1);
        marketAftersale.setAddTime(new Date());
        marketAftersale.setDeleted(false);
        marketAftersaleMapper.insertSelective(marketAftersale);
    }

    @Override
    public void delete(Integer orderId) {
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setDeleted(true);
        //marketOrder.setEndTime(new Date());
        marketOrderMapper.updateByExampleSelective(marketOrder, orderExample);

        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsExampleCriteria = orderGoodsExample.createCriteria();
        orderGoodsExampleCriteria.andOrderIdEqualTo(orderId);
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        marketOrderGoods.setDeleted(true);
        marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods, orderGoodsExample);
    }

    @Override
    public void confirm(Integer orderId) {
        //Integer statusId = 401;
        //marketOrderMapper.updateOrderStatus(orderId, statusId);
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short) 401);
        marketOrder.setConfirmTime(new Date());
        int comments = marketOrderGoodsMapper.countGoodsByOrderId(orderId);
        marketOrder.setComments((short)comments);
        marketOrderMapper.updateByExampleSelective(marketOrder, orderExample);
    }

    @Override
    public OrderDetailGoodsVO goods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoodsList = marketOrderGoodsMapper.selectByExample(example);
        List<OrderDetailGoodsVO> orderDetailGoodsVOS = MarketOrderDetailGoodsVOMapper.INSTANCE.po2Vo(marketOrderGoodsList);
        return orderDetailGoodsVOS.iterator().next();
    }

    /**
     * 根据购物车添加订单
     *
     * @param cartToOrderBO 需要使用参数：addressId,CartId,couponId,message,userCouponId
     */
    @Override
    public WXSubmitVO submit(CartToOrderBO cartToOrderBO) {
        //get userId
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer userId = marketUser.getId();
        //查找market_cart
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
        cartExampleCriteria.andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);
        //修改market_order表
        MarketOrder insertOrder = new MarketOrder();
        insertOrder.setUserId(userId);
        //设置orderSn
        // Date date = new Date();
        // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        // String orderSn = simpleDateFormat.format(date);
        // String time = String.valueOf(date.getTime());
        // int length = 16 - userId.toString().length();
        // orderSn = orderSn + userId + time.substring(length-length-1);
        String orderSn = OrderSnUtil.getOrderSn(userId);
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(cartToOrderBO.getAddressId());
        insertOrder.setOrderSn(orderSn);
        insertOrder.setOrderStatus((short) 101);
        insertOrder.setAftersaleStatus((short) 0);
        insertOrder.setConsignee(marketAddress.getName());
        insertOrder.setMobile(marketAddress.getTel());
        insertOrder.setAddress(marketAddress.getAddressDetail());
        insertOrder.setMessage(cartToOrderBO.getMessage());
        MarketOrder marketOrder = marketCartMapper.selectByUserId(userId);
        BigDecimal goodsPrice = marketOrder.getGoodsPrice();
        insertOrder.setGoodsPrice(goodsPrice);
        insertOrder.setGrouponPrice(BigDecimal.valueOf(0));
        MarketSystemExample marketSystemExample = new MarketSystemExample();
        marketSystemExample.createCriteria().andKeyNameEqualTo("market_express_freight_min");
        Integer freightMin = Integer.parseInt(marketSystemMapper.selectByExample(marketSystemExample).get(0).getKeyValue());
        MarketSystemExample marketSystemExample2 = new MarketSystemExample();
        marketSystemExample2.createCriteria().andKeyNameEqualTo("market_express_freight_value");
        Integer freightValue = Integer.parseInt(marketSystemMapper.selectByExample(marketSystemExample2).get(0).getKeyValue());
        Integer freight;
        if (goodsPrice.intValue() >= freightMin) {
            freight = 0;
        } else {
            freight = freightValue;
        }
        insertOrder.setFreightPrice(BigDecimal.valueOf(freight));//运费
        BigDecimal discount = BigDecimal.valueOf(0);
        if (cartToOrderBO.getCouponId() != 0 && cartToOrderBO.getCouponId() != -1) {
            discount = marketCouponMapper.selectByPrimaryKey(cartToOrderBO.getCouponId()).getDiscount();
        }
        insertOrder.setCouponPrice(discount);//优惠券优惠
        insertOrder.setIntegralPrice(BigDecimal.valueOf(0));//积分减免
        //insertOrder.setGrouponPrice();//团购优惠
        double orderPrice = goodsPrice.doubleValue() + freight.doubleValue() - discount.doubleValue();
        insertOrder.setOrderPrice(BigDecimal.valueOf(orderPrice));//不含积分订单价格
        insertOrder.setActualPrice(BigDecimal.valueOf(orderPrice));
        //insertOrder.setPayId();
        //insertOrder.setPayTime();
        //insertOrder.setShipSn();
        //insertOrder.setShipChannel();
        //insertOrder.setShipTime();
        //insertOrder.setRefundAmount();
        //insertOrder.setRefundContent();
        //insertOrder.setRefundType();
        //insertOrder.setRefundTime();
        //insertOrder.setConfirmTime();
        //insertOrder.setComments(marketOrder.getComments());//商品数量
        insertOrder.setComments((short)0);//商品数量
        //insertOrder.setEndTime();
        insertOrder.setAddTime(new Date());
        //insertOrder.setUpdateTime();
        insertOrder.setDeleted(false);
        marketOrderMapper.insertSelective(insertOrder);
        Integer orderId = insertOrder.getId();
        //修改market_coupon_user
        int couponId = cartToOrderBO.getCouponId();
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
        marketCouponUserExampleCriteria.andCouponIdEqualTo(couponId);
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setStatus((short) 1);
        marketCouponUserMapper.updateByExampleSelective(marketCouponUser, marketCouponUserExample);
        //修改order_goods
        List<MarketOrderGoods> marketOrderGoods = MarketCart2OrderGoodsMapper.INSTANCE.po2Vo(marketCarts);
        Iterator<MarketOrderGoods> iterator = marketOrderGoods.iterator();
        while (iterator.hasNext()) {
            MarketOrderGoods next = iterator.next();
            next.setId(null);
            next.setOrderId(orderId);
            marketOrderGoodsMapper.insertSelective(next);
        }
        WXSubmitVO wxSubmitVO = new WXSubmitVO();
        wxSubmitVO.setGrouponLinkId(0);
        wxSubmitVO.setOrderId(orderId);
        //market_cart
        MarketCartExample cartExample1 = new MarketCartExample();
        cartExample1.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true);
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        marketCartMapper.updateByExampleSelective(marketCart,cartExample1);
        return wxSubmitVO;
    }

    @Override
    public void prepay(Integer orderId) {
        // Integer statusId = 201;
        // marketOrderMapper.updateOrderStatus(orderId, statusId);
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short) 201);
        //marketOrder.setConfirmTime(new Date());
        marketOrderMapper.updateByExampleSelective(marketOrder, orderExample);
    }
}
